package com.lenovo.newsapp.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.lenovo.newsapp.R;
import com.lenovo.newsapp.model.HomeNews;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.ThreadPool;
import com.lenovo.newsapp.util.Tools;

public class HomeNewsListAdapter extends BaseAdapter {
	
	private static final String TAG = HomeNewsListAdapter.class.getSimpleName();
	private LayoutInflater inflater;
	private List<HomeNews> homeNewsList = new ArrayList<HomeNews>();
	private final Handler handler = new Handler();
	private ViewHolder holder = null;
	private Context context;
	private Bitmap bitmap;
	
	public HomeNewsListAdapter(Context context, List<HomeNews> info) {
		this.context = context;
		this.homeNewsList = info;
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	public void setData(List<HomeNews> homeNewsList) {
		this.homeNewsList.addAll(homeNewsList);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return homeNewsList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return homeNewsList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Log.i(TAG, "getView");
		Log.i(TAG, "convertView = " + convertView);
		Log.i(TAG, "position = " + position);
		if (null == convertView) {
			convertView = inflater.inflate(R.layout.home_list_item, null);
			holder = new ViewHolder();
			convertView.setTag(holder);
			holder.title = (TextView) convertView.findViewById(R.id.news_item_title);
			holder.summary = (TextView) convertView.findViewById(R.id.news_item_summary);
			holder.img = (ImageView) convertView.findViewById(R.id.news_item_thumbnail);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final HomeNews homeItem = homeNewsList.get(position);
		holder.title.setText(homeItem.getTitle());
		holder.summary.setText(homeItem.getSummary());
		
		ThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				try {
					bitmap = Tools.getBitMap(Const.DOMAIN+homeItem.getNewsThumbnail());
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.post(new Runnable() {
					@Override
					public void run() {
						holder.img.setImageBitmap(bitmap);
					}
				});
			}
		});

		return convertView;
	}

	class ViewHolder {
		TextView title;
		TextView summary;
		ImageView img;
	}

}
